package org.ciallo.simplemusicplayer.util;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import java.io.File;

import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.data.model.Song;
import timber.log.Timber;

public class RingtoneUtil {

    /**
     * 检查是否有修改系统设置的权限
     */
    public static boolean canWriteSettings(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return Settings.System.canWrite(context);
        }
        return true; // API 23以下不需要特殊权限
    }

    /**
     * 请求修改系统设置的权限 (跳转到系统设置页面)
     */
    public static void requestWriteSettingsPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(context)) {
                new AlertDialog.Builder(context)
                        .setTitle("权限请求")
                        .setMessage("设置铃声需要修改系统设置的权限，请在接下来的设置页面中允许。")
                        .setPositiveButton(R.string.go_to_settings, (dialog, which) -> {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                            intent.setData(Uri.parse("package:" + context.getPackageName()));
                            context.startActivity(intent);
                        })
                        .setNegativeButton(R.string.cancel, null)
                        .show();
            }
        }
    }

    /**
     * 设置歌曲为铃声
     * @param context Context
     * @param song 要设置为铃声的歌曲对象
     * @param type RingtoneManager.TYPE_RINGTONE, TYPE_NOTIFICATION, TYPE_ALARM
     * @return 是否成功设置
     */
    public static boolean setRingtone(Context context, Song song, int type) {
        if (!canWriteSettings(context)) {
            Toast.makeText(context, "没有修改系统设置的权限，无法设置铃声。", Toast.LENGTH_LONG).show();
            requestWriteSettingsPermission(context); // 提示用户去授权
            return false;
        }

        File ringtoneFile = new File(song.getPath());
        if (!ringtoneFile.exists()) {
            Toast.makeText(context, "歌曲文件不存在。", Toast.LENGTH_SHORT).show();
            return false;
        }

        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, ringtoneFile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, song.getTitle());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*"); // 或更具体的 MIME_TYPE，如 song.mimeType
        values.put(MediaStore.Audio.Media.ARTIST, song.getArtistName());
        values.put(MediaStore.Audio.Media.IS_RINGTONE, type == RingtoneManager.TYPE_RINGTONE);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, type == RingtoneManager.TYPE_NOTIFICATION);
        values.put(MediaStore.Audio.Media.IS_ALARM, type == RingtoneManager.TYPE_ALARM);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false); // 标记为非音乐库中的普通音乐

        Uri uri = MediaStore.Audio.Media.getContentUriForPath(ringtoneFile.getAbsolutePath());
        Uri newUri = null;
        // 先尝试删除已存在的相同路径的记录，避免重复插入导致问题
        try {
            if (uri != null) {
                context.getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=?", new String[]{ringtoneFile.getAbsolutePath()});
            }
        } catch (Exception e) {
            Timber.w(e, "Error deleting old ringtone entry for path: %s", ringtoneFile.getAbsolutePath());
        }

        try {
            if (uri != null) {
                newUri = context.getContentResolver().insert(uri, values);
            }
            if (newUri != null) {
                RingtoneManager.setActualDefaultRingtoneUri(context, type, newUri);
                String typeName = "";
                if (type == RingtoneManager.TYPE_RINGTONE) typeName = "来电铃声";
                else if (type == RingtoneManager.TYPE_NOTIFICATION) typeName = "通知铃声";
                else if (type == RingtoneManager.TYPE_ALARM) typeName = "闹钟铃声";
                Toast.makeText(context, song.getTitle() + " 已设为" + typeName, Toast.LENGTH_SHORT).show();
                return true;
            } else {
                Toast.makeText(context, "设置铃声失败：无法插入媒体记录", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Timber.e(e, "Error setting ringtone");
            Toast.makeText(context, "设置铃声失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
        return false;
    }
}